package com.baseweb.webadmin.core.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CheckCodeUtil
{
    private static Map<String, String> checkCodeMap = new ConcurrentHashMap<String, String>();
    
    /**
     * 
     * newCheckCode:根据手机号码生成一个验证码并存入map缓存. <br/> 
     * 
     * @author caodejun[caodejun@imimz.com]
     * @param phone
     * @return 
     * @since JDK 1.7
     */
    public static String newCheckCode(String phone)
    {
        StringBuffer checkCode = new StringBuffer();
        while(checkCode.length() < 6)
        {
            checkCode.append((int)(Math.random() * 10));
        }
        checkCodeMap.put(phone, checkCode + "-" + System.currentTimeMillis());
        return checkCode.toString();
    }
    
    
    public static void removeCheckCode(String phone){
    	checkCodeMap.remove(phone);
    }
    
    
    public static String getCheckCode(String phone){
    	if(null == checkCodeMap || checkCodeMap.isEmpty()){
    		return null;
    	}
    	String checkCode = CheckCodeUtil.checkCodeMap.get(phone);
    	if(checkCode!=null){
    		return checkCode;
    	}else{
    		return null;
    	}
    	
    }
    
    
    public static String verify(String phone, String verify) {
		// 电话号码去找校验码
		String codeAndTime = (String) CheckCodeUtil.getCheckCode(phone);
		if (codeAndTime == null) {
			return "没有获取验证码";
		}
		String oldCode = String.valueOf(codeAndTime.split("-")[0]);
		Long oldTime = Long.valueOf(codeAndTime.split("-")[1]);
		Long newTime = System.currentTimeMillis();
		if ((newTime - oldTime) / 1000 > 300) // 5min
		{
			return "验证码失效";
		}
		if (!oldCode.equals(verify)) {

			return "验证码错误";
		}
		CheckCodeUtil.removeCheckCode(phone);
		return "1";
	}
}
